package com.monitor.log.biz;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.filter.GenericFilterBean;

import com.monitor.log.biz.core.BizLogData;
import com.monitor.log.biz.core.BizLogTraceIdUtil;
import com.system.comm.utils.FrameStringUtil;

/**
 * 使用时需要在项目中注入bean
	@Bean
	public BizLogFilter bizLogFilter() {
		return new BizLogFilter();
	}
 * @author yuejing
 *
 */
@WebFilter(urlPatterns = "/*", filterName = "bizLogFilter")
public class BizLogFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //traceId初始化
        initTraceId((HttpServletRequest) servletRequest);
        //执行后续过滤器
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * traceId初始化
     */
    private void initTraceId(HttpServletRequest request) {
        //尝试获取http请求中的traceId
        String traceId = request.getParameter(BizLogData.MS_TRACE_ID);
        if (FrameStringUtil.isEmpty(traceId)) {
        	traceId = request.getHeader(BizLogData.MS_TRACE_ID);
        }
        //如果当前traceId为空或者为默认traceId，则生成新的traceId
        if (FrameStringUtil.isEmpty(traceId) || BizLogTraceIdUtil.defaultTraceId(traceId)) {
            traceId = BizLogTraceIdUtil.genTraceId();
        }

        //设置traceId
        BizLogTraceIdUtil.setTraceId(traceId);
    }
}